<template>
  <div class="bom-list-page">
    <div class="page-title">BOM管理</div>

    <el-card class="toolbar-card" shadow="never">
      <div class="toolbar">
        <div class="left">
          <el-button type="primary" @click="onAdd">新增</el-button>
          <el-button @click="onImportClick">导入</el-button>
          <el-button @click="onDownloadTpl">下载模版</el-button>
        </div>
        <div class="right">
          <el-input v-model="q" placeholder="请搜索" clearable style="width: 360px">
            <template #suffix>
              <el-icon class="clickable" @click="onQuickSearch"><Search /></el-icon>
            </template>
          </el-input>
          <el-button class="square" @click="toggleAdvanced" :title="showAdvanced ? '收起筛选' : '展开筛选'">
            <el-icon><Menu /></el-icon>
          </el-button>
        </div>
      </div>

      <transition name="el-zoom-in-top">
        <div v-show="showAdvanced" class="advanced-panel">
          <el-row :gutter="20">
            <el-col :md="12" :sm="24">
              <el-form-item label="BOM编号"><el-input v-model="filters.code" placeholder="请输入" clearable /></el-form-item>
            </el-col>
            <el-col :md="12" :sm="24">
              <el-form-item label="BOM主题"><el-input v-model="filters.subject" placeholder="请输入" clearable /></el-form-item>
            </el-col>

            <el-col :md="12" :sm="24">
              <el-form-item label="默认BOM">
                <el-select v-model="filters.isDefault" placeholder="请选择" clearable>
                  <el-option label="是" :value="true" />
                  <el-option label="否" :value="false" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :md="12" :sm="24">
              <el-form-item label="版本"><el-input v-model="filters.version" placeholder="请输入" clearable /></el-form-item>
            </el-col>

            <el-col :md="12" :sm="24">
              <el-form-item label="成品类型">
                <el-select v-model="filters.productType" placeholder="请选择" clearable>
                  <el-option label="成品" value="FG" />
                  <el-option label="半成品" value="SFG" />
                  <el-option label="其他" value="OTH" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :md="12" :sm="24">
              <el-form-item label="成品名称"><el-input v-model="filters.productName" placeholder="请输入" clearable /></el-form-item>
            </el-col>

            <el-col :md="12" :sm="24">
              <el-form-item label="日产量">
                <div class="range">
                  <el-input-number v-model="filters.dailyMin" :min="0" controls-position="right" placeholder="最小值" />
                  <span class="range-sep">~</span>
                  <el-input-number v-model="filters.dailyMax" :min="0" controls-position="right" placeholder="最大值" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="adv-actions">
            <el-button @click="toggleAdvanced">关闭</el-button>
            <el-button @click="onResetAdvanced">清空</el-button>
            <el-button type="primary" @click="onApplyAdvanced">查询</el-button>
          </div>
        </div>
      </transition>
    </el-card>

    <el-card class="table-card" shadow="never">
      <el-table :data="list" border stripe style="width: 100%" @selection-change="onSelChange" :loading="loading">
        <el-table-column type="selection" width="48" />
        <el-table-column label="序号" type="index" width="60" :index="indexMethod" />
        <el-table-column prop="code" label="BOM编号" width="120" />
        <el-table-column prop="subject" label="BOM主题" min-width="160" />
        <el-table-column prop="productCode" label="成品编码" width="120" />
        <el-table-column prop="productName" label="成品名称" min-width="140" />
        <el-table-column prop="model" label="规格型号" min-width="140" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="category" label="品类" width="100" />
        <el-table-column prop="isDefault" label="默认BOM" width="100">
          <template #default="{ row }">{{ renderYesNo(row.isDefault) }}</template>
        </el-table-column>
        <el-table-column prop="dailyOutput" label="日产量" width="120">
          <template #default="{ row }">{{ formatQty(row.dailyOutput) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text size="small" @click="onEdit(row)">编辑</el-button>
            <el-button type="danger" text size="small" @click="onDelete(row)">删除</el-button>
            <el-button type="info" text size="small" @click="onView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pager">
        <div class="left">共{{ total }} 条数据</div>
        <div class="right">
          <el-select v-model="pageSize" size="small" style="width: 100px; margin-right: 8px;">
            <el-option :value="5" label="5条/页" />
            <el-option :value="10" label="10条/页" />
            <el-option :value="20" label="20条/页" />
          </el-select>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            v-model:current-page="currentPage"
          />
        </div>
      </div>
    </el-card>
  </div>
  <input ref="fileInput" type="file" accept=".xlsx,.csv" style="display:none" @change="onFileChange" />
</template>

<script setup lang="ts">
import { computed, ref, watch, onMounted } from 'vue'
import { Refresh, Search, Menu } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import ERP from '@/utils/Interceptors'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 搜索
const q = ref('')
const showAdvanced = ref(false)
const filters = ref<{ code?: string; subject?: string; isDefault?: boolean | undefined; version?: string; productType?: string; productName?: string; dailyMin?: number | undefined; dailyMax?: number | undefined }>({})

// 列表数据：默认空，待对接后端接口加载
const list = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const loading = ref(false)
const fileInput = ref<HTMLInputElement | null>(null)

async function loadList() {
  loading.value = true
  try {
    const { data } = await ERP.get('/api/Boms', {
      params: {
        kw: q.value || undefined,
        code: filters.value.code || undefined,
        subject: filters.value.subject || undefined,
        isDefault: filters.value.isDefault,
        version: filters.value.version || undefined,
        productType: filters.value.productType || undefined,
        productName: filters.value.productName || undefined,
        // dailyMin/dailyMax 当前后端未实现
        page: currentPage.value,
        pageSize: pageSize.value,
      }
    })
    const paging = data?.data || {}
    list.value = paging.data || []
    total.value = paging.totalCount || 0
  } finally {
    loading.value = false
  }
}

function indexMethod(index: number) {
  return (currentPage.value - 1) * pageSize.value + index + 1
}

function onRefresh() {
  q.value = ''
  currentPage.value = 1
  loadList()
}
function onSelChange(_rows: any[]) {}
function onAdd() {
  router.push({ name: 'BOMCreate' })
}
function onEdit(row: any) {
  router.push({ name: 'BOMEdit', query: { id: row.id } })
}
function onDelete(row: any) {
  ElMessageBox.confirm(`确认删除该BOM（${row.code}）吗？`, '提示', { type: 'warning' })
    .then(async () => {
      await ERP.delete(`/api/Boms/${row.id}`)
      ElMessage.success('删除成功')
      loadList()
    })
    .catch(() => {})
}
function onView(row: any) {
  router.push({ name: 'BOMDetails', query: { id: row.id } })
}

function toggleAdvanced() { showAdvanced.value = !showAdvanced.value }
function onQuickSearch() { currentPage.value = 1; loadList() }
function onResetAdvanced() { filters.value = {}; currentPage.value = 1; loadList() }
function onApplyAdvanced() { currentPage.value = 1; showAdvanced.value = false; loadList() }

function onImportClick() {
  fileInput.value?.click()
}

async function onFileChange(e: Event) {
  const input = e.target as HTMLInputElement
  const file = input.files && input.files[0]
  if (!file) return
  try {
    const fd = new FormData()
    fd.append('file', file)
    const { data } = await ERP.post('/api/Boms/import', fd, { headers: { 'Content-Type': 'multipart/form-data' } })
    ElMessage.success(data?.msg || '导入完成')
    loadList()
  } catch (err: any) {
    ElMessage.error(err?.response?.data?.msg || err?.message || '导入失败')
  } finally {
    if (input) input.value = ''
  }
}

async function onDownloadTpl() {
  try {
    const res = await ERP.get('/api/Boms/template', { responseType: 'blob' })
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `BOM_Template_${new Date().toISOString().slice(0,10)}.xlsx`
    document.body.appendChild(a)
    a.click()
    a.remove()
    URL.revokeObjectURL(url)
  } catch (err: any) {
    ElMessage.error(err?.response?.data?.msg || err?.message || '下载失败')
  }
}

function renderYesNo(v: any) {
  if (typeof v === 'boolean') return v ? '是' : '否'
  if (typeof v === 'string') {
    const s = v.trim().toLowerCase()
    if (s === '是' || s === 'yes' || s === 'true' || s === 'y' || s === '1') return '是'
    if (s === '否' || s === 'no' || s === 'false' || s === 'n' || s === '0') return '否'
  }
  if (typeof v === 'number') return v === 1 ? '是' : '否'
  return '否'
}

function formatQty(v: number | null | undefined) {
  if (v === null || v === undefined) return '-'
  const n = Number(v)
  if (Number.isNaN(n)) return '-'
  // 使用本地化格式，最多4位小数，最少0位，自动去掉多余尾零
  return n.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 4 })
}

watch([currentPage, pageSize], () => loadList())
onMounted(() => loadList())
</script>

<style scoped>
.bom-list-page {
  padding: 12px;
}
.page-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
}
.toolbar-card { margin-bottom: 12px; }
.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.toolbar .left > * { margin-right: 8px; }
.toolbar .right { display: flex; align-items: center; gap: 8px; }
.toolbar .right .square { width: 36px; height: 36px; padding: 0; }
.clickable { cursor: pointer; }

.advanced-panel {
  margin-top: 12px;
  padding: 12px;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 6px;
}
.advanced-panel .el-form-item { margin-bottom: 10px; }
.range { display: flex; align-items: center; }
.range-sep { margin: 0 8px; color: #999; }

.table-card { margin-top: 8px; }
.pager {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
}
.right { display: flex; align-items: center; }
</style>
